import { ref } from "vue";
import { defineStore } from "pinia";
import { useLockscreenStore } from "./lockscreen";
import { useSSEStore } from "./sse";
import type { RouteRecordRaw } from "vue-router";
import { resetRouter } from "@/router";
import { generateDynamicRoutes } from "@/router/helper/routeHelper";
import api from "@/api/";
import router from "@/router/";
import { Gender } from "@/enums";
import helper from "@/utils/helper";
// 权限列表仅作为备用
import { permissions as defaultPermissions } from "@/constants/data";
export const useUserStore = defineStore(
    "user",
    () => {
        const sseStore = useSSEStore();
        const lockscreenStore = useLockscreenStore();
        const token = ref<string>();
        const perms = ref<string[]>([]);
        const menus = ref<RouteRecordRaw[]>([]);
        const userInfo = ref<Nullable<UserOut>>(null);

        const sortMenus = (menus: RouteRecordRaw[] = []) => {
            return menus
                .filter((n) => {
                    const flag = !n.meta?.hideInMenu;
                    if (flag && n.children?.length) {
                        n.children = sortMenus(n.children);
                    }
                    return flag;
                })
                .sort((a, b) => ~~Number(a.meta?.orderNo) - ~~Number(b.meta?.orderNo));
        };

        /** 清空登录态(token、userInfo...) */
        const clearLoginStatus = () => {
            token.value = "";
            perms.value = [];
            menus.value = [];
            userInfo.value = null;
            resetRouter();
            setTimeout(() => {
                localStorage.clear();
            });
        };
        /** 登录 */
        const login = async (input: UserInput) => {
            helper.laoding("登录中");
            let result = await api.user.token(input);
            if (result != null) {
                token.value = result;
                await afterLogin();
                lockscreenStore.setLock(false);
                lockscreenStore.saveLoginPwd(input.pwd);
                router.push("/");
            }
            helper.destroy();
        };

        /** 登录成功之后, 获取用户信息以及生成权限路由 */
        const afterLogin = async () => {
            try {
                var result = await api.user.current();
                if (result != null) {
                    if (result.avatar == null) {
                        result.avatar = helper.toUrl(result.gender == Gender.Male ? "icon/male.png" : "icon/female.png");
                    }
                    userInfo.value = result;
                }
                await fetchPermsAndMenus();
                // sseStore.initServerMsgListener();
            } catch (error) {
                return Promise.reject(error);
                // return logout();
            }
        };
        /** 获取权限及菜单 */
        const fetchPermsAndMenus = async () => {
            try {
                // 获取菜单数据
                const menusData = await api.account.accountMenu();
                
                // 获取权限数据
                const permissionsData = await api.account.accountPermissions();
                
                // 设置权限和菜单
                perms.value = permissionsData || [];
                const result = generateDynamicRoutes(menusData as unknown as RouteRecordRaw[]);
                menus.value = sortMenus(result);
            } catch (error) {
                console.error('获取菜单和权限数据失败:', error);
                // 出错时使用本地默认数据
                // const { menus: cmenus } = await import('@/constants/data');
                // const menusData = cmenus;
                // perms.value = defaultPermissions;
                const result = generateDynamicRoutes([] as unknown as RouteRecordRaw[]);
                menus.value = sortMenus(result);
            }
        };
        /** 登出 */
        const logout = async () => {
            // await Api.account.accountLogout();
            sseStore.closeEventSource();
            clearLoginStatus();
        };

        return {
            token,
            perms,
            menus,
            userInfo,
            login,
            afterLogin,
            logout,
            clearLoginStatus,
            fetchPermsAndMenus,
        };
    },
    {
        persist: {
            pick: ["token"],
        },
    }
);
